package top.eggcode.system.modules.log.control;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.web.bind.annotation.*;
import top.eggcode.common.base.SessionBaseController;
import top.eggcode.common.model.ResponseResult;
import top.eggcode.common.mvc.Responser;
import top.eggcode.common.thread.AsyncExecutor;
import top.eggcode.system.modules.log.model.VisitLogEntity;
import top.eggcode.system.modules.log.model.VisitLogQuery;
import top.eggcode.system.modules.log.model.VisitLogView;
import top.eggcode.system.modules.log.service.VisitLogServiceImpl;

/**
 * Title:
 * Description: TODO
 * Date: 2021/5/27 13:44
 *
 * @author JiaQi Ding
 * @version 1.0
 */
@Api(tags = "页面访问日志")
@AllArgsConstructor
@RequestMapping("/api/log/visit")
@RestController
public class VisitLogController extends SessionBaseController {

    private final VisitLogServiceImpl selfService;

    private final AsyncExecutor executor;

    @GetMapping("{id}")
    public ResponseResult<?> get(@PathVariable String id) {
        return super.pack(selfService.get(id).get(), VisitLogView.class);
    }

    @ApiOperation("列表分页")
    @GetMapping("list/page")
    public ResponseResult<?> listPage(VisitLogQuery query) {
        return super.pack(selfService.page(query), VisitLogView.class);
    }

    @PostMapping("add")
    public ResponseResult<?> add(@RequestBody VisitLogView view) throws Exception {
        VisitLogEntity entity = view.convert();
        String username = this.getUsername();
        entity.setUsername(username == null ? "#visitor" : username);
        // 异步执行
        executor.commit(selfService::put, entity);
        return Responser.successful();
    }
}
